<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Agent;
use app\madmin\model\AgentApply;
use app\madmin\model\AgentGrade as admin;
use app\madmin\validate\AgentGradeValidate;
use app\utils\TrimData;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;

class AgentGradeService
{
    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\excception\DbException
     */
    public function findAll()
    {
        $list = admin::group('id')->select();
        return [HTTP_SUCCESS, $list];
    }

    /**
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }

    /**
     * 新增
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
        try {
            validate(AgentGradeValidate::class)->scene("save")->check($data);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getMessage());
        }
        admin::create($data);
        return [HTTP_CREATED, 1];
    }

    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {
        $admin = admin::withTrashed()->find($id);
        if (is_null($admin)) {
            $data['id'] = $id;
            return $this->save($data);
        }
        $grade = admin::onlyTrashed()->find($id);
        if (isset($data['status']) && $data['status'] == 1 && !is_null($grade)) {
            $grade->restore();
        }
        $admin = admin::where('id', $id)
            ->update($data);
        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     * @throws
     */
    public function delete($id)
    {
        $a = Agent::where('grade_id', $id)->find();
        if (!empty($a)) {
            throw new Exception("等级正在使用中！不可删除", HTTP_NOTACCEPT);
        }
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

}
